<script setup>
import Toolbar from "@/components/Toolbar.vue";
import { getButtonList } from "@/utils/index";
import { useRoute } from "vue-router";
import { useUserStore } from "@/stores/userStore";
import { onMounted, ref } from "vue";
import { getRoleList,addRole,editRole,delRole } from "@/apis/role";
import util from "@/utils/date.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { getDepartmentTree } from "@/apis/department";

const route = useRoute();
const userStore = useUserStore();
// 当前登录用户拥有的按钮列表
const buttonList = getButtonList(route.path, userStore.userMenuPermissions);

// 用户列表
const userList = ref([]);
// 显示添加弹框标记
const showDialogForm = ref(false);
// 添加和编辑区分标记
let isEdit = ref(false);

// 请求数据列表参数
const parms = ref({
  page: 0,
  pageSize: 5,
  currentPage: 1,
  total: 0,
  key: "",
});
// 获取用户列表
const getRoles = async () => {
  const res = await getRoleList(parms.value);
  console.log(res);
  parms.value.total = res.dataCount;
  userList.value = res.data;
};
// 格式化时间
const formatBirth = (row, column, cellValue) => {
  // console.log(row, column, cellValue)
  // return !row.createTime || row.createTime == ""
  //   ? ""
  //   : util.formatDate.format(new Date(row.createTime), "yyyy-MM-dd");
  return cellValue&&util.formatDate.format(new Date(cellValue),'yyyy-MM-dd')
};
onMounted(() => {
  getRoles();
  getDepartment()
});
// 表格id
const tableRef = ref(null);
// 当前选择行
const currentRow = ref(null);
// form引用
const ruleFormRef = ref(null);
// 单位数据集合
const options = ref([]);

// 获取部门列表
const getDepartment = async () => {
  const res = await getDepartmentTree({ pid: 0 });
  // console.log(res);
  options.value.push(res);
};

const selectRow = (selection, row) => {
  console.log(selection, row);
  currentRow.value = null;
  tableRef.value.clearSelection();
  if (selection.length == 0) {
    return;
  }
  if (row) selectCurrentRow(row);
};
// 点击行勾选复选框
const selectCurrentRow = (val) => {
  // console.log(val);
  currentRow.value = val;
  tableRef.value.clearSelection();
  tableRef.value.toggleRowSelection(val, true);
};
// 点击按钮事件
const buttonClick = (item) => {
  console.log(item);
  parms.value.key = item.search;
  if (item.func == "handleAdd") {
    isEdit.value = false;
    handleAdd();
  } else if (item.func == "handleEdit") {
    handleEdit();
    isEdit.value = true;
  } else if (item.func == "handleDel") {
    handleDelete();
  } else if (item.func == "getRoles") {
    getRoles();
  }
};
// 添加/编辑表单数据
let dialogForm = ref({
  id: 0,
  name:'',
  authorityScope:-1,
  dids: '',
  enabled:false,
  description:''
});
const rules = ref({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  enabled: [{ required: true, message: "请选择状态", trigger: "blur" }],
});
// 点击添加按钮弹框form表单
const handleAdd = async () => {
  dialogForm.value = {
    id: 0,
    name:'',
    authorityScope:-1,
    dids: '',
    enabled:false,
    description:''
  };
  showDialogForm.value = true;
};

// 编辑弹框
const handleEdit = async () => {
  if (currentRow.value) {
    dialogForm.value = Object.assign({}, currentRow.value);
    showDialogForm.value = true;
  } else {
    ElMessage.warning("请选择要编辑的数据");
  }
};

// 提交表单
const submitForm = () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let msg = "添加成功";
      if (isEdit.value) {
        await editRole(dialogForm.value);
        msg = "编辑成功";
      } else {
        await addRole(dialogForm.value);
      }
      ElMessage.success(msg);
      parms.value.page = 0;
      parms.value.currentPage = 1;
      getRoles();
      resetForm();
    } else {
      console.error("error submit", fields);
    }
  });
};

// 取消表单
const resetForm = () => {
  showDialogForm.value = false;
  ruleFormRef.value.clearValidate();
  ruleFormRef.value.resetFields();
};

// 删除
const handleDelete = async () => {
  if (currentRow.value) {
    ElMessageBox.confirm("确定要删除吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        await delRole({ id: currentRow.value.id });
        ElMessage.success("删除成功");
        getRoles();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "Delete canceled",
        });
      });
  } else {
    ElMessage.warning("请选择要编辑的数据");
  }
};

// 分页改变
const handleCurrentChange = (page) => {
  // console.log(page);
  parms.value.page = page;
  parms.value.currentPage = page;
  getRoles()
};
// 解决 vscode 格式化vue问题 https://zhuanlan.zhihu.com/p/429676466
/**
 *  "vetur.format.defaultFormatter.html": "js-beautify-html",
    "vetur.format.defaultFormatterOptions": {
        "js-beautify-html": {
            "indent_with_tabs": false,
            "wrap_line_length": 150,
            // - auto: 仅在超出行长度时才对属性进行换行。
            // - force: 对除第一个属性外的其他每个属性进行换行。
            // - force-aligned: 对除第一个属性外的其他每个属性进行换行，并保持对齐。
            // - force-expand-multiline: 对每个属性进行换行。
            // - aligned-multiple: 当超出折行长度时，将属性进行垂直对齐。
            "wrap_attributes": "aligned-multiple"
        },
     }
 */
</script>

<template>
  <Toolbar :button-list="buttonList" @call-function="buttonClick"></Toolbar>
  <el-table :data="userList" @select="selectRow" @row-click="selectCurrentRow" border ref="tableRef">
    <el-table-column type="selection" width="50"></el-table-column>
    <el-table-column type="index" width="80" label="序号"></el-table-column>
    <el-table-column prop="name" label="角色名称" sortable></el-table-column>
    <el-table-column prop="AuthorityScope" label="权限范围" width sortable>
      <template #default="scope">
        <el-tag type="danger" v-if="scope.row.authorityScope == null">无任何数据权限</el-tag>
        <el-tag v-if="scope.row.authorityScope == 1">自定义数据权限 <br />{{ scope.row.Dids }}</el-tag>
        <el-tag v-if="scope.row.authorityScope == 2">本部门数据权限</el-tag>
        <el-tag type="warning" v-if="scope.row.authorityScope == 3">本部门及以下所有部门</el-tag>
        <el-tag v-if="scope.row.authorityScope == 4">仅自己数据权限</el-tag>
        <el-tag type="success" v-if="scope.row.authorityScope == 9">全部数据权限</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="description" label="说明" sortable></el-table-column>
    <el-table-column prop="createTime" label="创建时间" :formatter="formatBirth" sortable></el-table-column>
    <el-table-column prop="enabled" label="状态" width="" sortable>
      <template #default="scope">
        <el-tag :type="scope.row.enabled? 'success' : 'danger'" disable-transitions>{{ scope.row.enabled  ? "正常" : "禁用" }}
        </el-tag>
      </template>
    </el-table-column>
  </el-table>
  <el-col :span="24" class="toolbar">
    <el-pagination background layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="parms.pageSize" :total="parms.total"
                   :current-page="parms.currentPage" style="float: right">
    </el-pagination>
  </el-col>
  <el-dialog v-model="showDialogForm" :title="isEdit == true ? '编辑角色' : '添加角色'" :close-on-click-modal="false" @close="resetForm">
    <el-form ref="ruleFormRef" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon :model="dialogForm">
      <el-form-item label="角色名" prop="name">
        <el-input v-model="dialogForm.name" />
      </el-form-item>
      <el-form-item label="权限范围" prop="authorityScope">
        <el-select v-model="dialogForm.authorityScope" placeholder="请选择权限范围">
          <el-option label="无任何数据权限" :value="-1"></el-option>
          <el-option label="自定义数据权限" :value="1"></el-option>
          <el-option label="本部门数据权限" :value="2"></el-option>
          <el-option label="本部门及以下所有部门" :value="3"></el-option>
          <el-option label="仅自己数据权限" :value="4"></el-option>
          <el-option label="全部数据权限" :value="9"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门权限" prop="dids" v-if="dialogForm.authorityScope==1">
        <el-tree :data="options" ref="treeAdd" default-expand-all show-checkbox node-key="value" :expand-on-click-node="true" :check-strictly="true"
                 :props="defaultProps"></el-tree>
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-radio-group v-model="dialogForm.enabled">
          <el-radio :value="true">激活</el-radio>
          <el-radio :value="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="说明" prop="description">
        <el-input type="textarea" v-model="dialogForm.description"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>